package com.cubic.auth.config;

import com.cubic.auth.filter.JwtTokenFilter;
import com.cubic.auth.jwt.GovernPasswordEncoder;
import com.cubic.auth.service.UserService;
import com.cubic.auth.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @ClassName MatrixSecurityConfig
 * @Author QIANGLU
 * @Date 2020/11/17 4:09 下午
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
public class GovernSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserService userService;



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //对请求进行认证  url认证配置顺序为：1.先配置放行不需要认证的 permitAll() 2.然后配置 需要特定权限的 hasRole() 3.最后配置 anyRequest().authenticated()
                .authorizeRequests()
                .antMatchers(getIncludePathPatterns()).permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .successForwardUrl("/user/list");

        //使用自定义的 Token过滤器 验证请求的Token是否合法
        http.addFilterBefore(new JwtTokenFilter(authenticationManagerBean(),userService), UsernamePasswordAuthenticationFilter.class);
        http.headers().cacheControl();
    }



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userService).passwordEncoder(new GovernPasswordEncoder());
        auth.eraseCredentials(false);
    }



    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    /**
     * 需要用户和服务认证判断的路径
     *
     * @return
     */
    private String[] getIncludePathPatterns() {
        String[] urls = {
                "/auth/**",
                "/druid/**",
                "/sys/login",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/webjar/springfox-swagger-ui/**",
                "/actuator/**"
        };
        return urls;
    }
}
